package io.gitee.hechenl.fastiotreport.controller.converter;

import io.gitee.hechenl.fastiotreport.domain.model.ConfigMetric;
import io.gitee.hechenl.fastiotreport.domain.model.ConfigMetricGroup;
import io.gitee.hechenl.fastiotreport.domain.vo.MetricVO;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

public class MetricConverter {

    @Getter
    @AllArgsConstructor
    public static class WithGroup {
        private Long groupId;
        private String groupName;
        private ConfigMetric configMetric;
        private BigDecimal metricValue;
    }

    private static List<WithGroup> groupList(
            Map<ConfigMetric, BigDecimal> metricMap, List<ConfigMetricGroup> allGroupList) {

        Map<Long, String> groupNameMap = CollectionUtils.isEmpty(allGroupList) ? Collections.emptyMap() :
                allGroupList.stream().collect(
                        Collectors.toMap(ConfigMetricGroup::getId, ConfigMetricGroup::getGroupName));

        List<WithGroup> list = new ArrayList<>();
        metricMap.forEach((metric, metricValue) -> {
            if (StringUtils.hasText(metric.getMetricGroup())) {
                List<Long> groupIds = Arrays.stream(
                        metric.getMetricGroup().split(",")).map(String::trim).map(Long::parseLong)
                        .collect(Collectors.toList());
                for (Long groupId : groupIds) {
                    list.add(new WithGroup(groupId, groupNameMap.get(groupId), metric, metricValue));
                }
            } else {
                list.add(new WithGroup(null, null, metric, metricValue));
            }
        });
        return list;
    }

    public static MetricVO toVO(Map<ConfigMetric, BigDecimal> metricMap, List<ConfigMetricGroup> allGroupList) {
        MetricVO VO = new MetricVO();
        if (CollectionUtils.isEmpty(metricMap)) {
            VO.setGroupMetricList(Collections.emptyList());
            return VO;
        }
        List<WithGroup> withGroups = groupList(metricMap, allGroupList);
        VO.setGroupMetricList(toGroupMetric(withGroups));
        return VO;
    }

    private static List<MetricVO.GroupMetric> toGroupMetric(
            List<WithGroup> withGroups) {
        return withGroups.stream().map(group -> {
            MetricVO.GroupMetric groupMetric = new MetricVO.GroupMetric();
            if (group.getGroupId() == null) {
                groupMetric.setMetricGroup("无所属分组");
            } else {
                groupMetric.setMetricGroup(group.getGroupName());
            }
            groupMetric.setMetricName(group.getConfigMetric().getMetricName());
            groupMetric.setValue(group.getMetricValue());
            return groupMetric;
        }).collect(Collectors.toList());
    }
}
